/**
   vis_server.h - Created by Timothy Morey on 1/27/2012.

   This file contains the definition for the VisServer object, which exports
   the visualization of this model to a client.
*/

#ifndef __VIS_SERVER_H
#define __VIS_SERVER_H

#include <pthread.h>

/**
   The VisServer object serves image frames generated from the simulation to a
   remote client via TCP.
*/
class VisServer
{
public:
  VisServer(unsigned short port);
  ~VisServer();

public:

  /**
     Sets the image buffer that the VisServer will serve up.  The image data will
     only be read by the VisServer, and it is assumed that the underlying buffer
     will be regularly updated.  If the size of the buffer changes, then SetImage
     should be called again to update the dimensions.

     @param img An array of width * height * 4 bytes, each of which represents a
     single channel in an rgba image.  Setting this to 0 will stop the VisServer
     from serving images.
     @param width The width of the image, in pixels.
     @param height The height of the image, in pixels.
   */
  void SetImage(unsigned char* img, unsigned short width, unsigned short height);
  
  /**
     Informs the VisServer that the image buffer has been updated and the new image
     should be served up.
  */
  void SetDirty();

  /**
     Informs the VisServer that the image buffer has been updated, and then
     blocks the calling thread until the image has been served up.  This ensures
     that each frame makes it to the client.
  */
  void SetDirtyAndBlock();

  void Start();
  void Stop();

protected:
  static void* ThreadEntryPoint(void* arg);
  void ThreadLoop();

protected:
  pthread_t _ThreadID;
  unsigned short _Port;  
  bool _KeepLooping;

  unsigned char* _Image;
  unsigned short _ImageWidth;
  unsigned short _ImageHeight;
  bool _Dirty;
  pthread_mutex_t _ImageMutex;
};

#endif
